<template>
    <view class="page-container">
        <navigation-bar :back="true" title="我的游戏"></navigation-bar>
        
        <!-- 修改scroll-view的样式和属性 -->
        <scroll-view 
            scroll-y 
            class="scroll-view"
            :refresher-triggered="isRefreshing"
            @scrolltolower="loadMore"
            refresher-enabled
            @refresherrefresh="onRefresh"
            :lower-threshold="100"
        >
            <!-- 游戏列表 -->
            <view class="game-list">
                <view class="game-item" v-for="(item, index) in myGame" :key="index">
                    <view class="game-content">
                        <view class="game-logo">
                            <image :src="item.kyyGameLogo || item.logoSquare || '/static/images/default-game.png'" 
                                  mode="aspectFill" class="logo-image" />
                        </view>
                        <view class="game-info">
                            <view class="game-name">{{ item.kyyGameAppname || item.appname }}</view>
                            <view class="game-desc">{{ item.briefIntro || '暂无介绍' }}</view>
                            <view class="game-stats">
                                <view class="stat-group">
                                    <view class="stat-item">{{ item.clickCount ? item.clickCount / 16 + '万+玩过' : '0人玩过' }}</view>
                                </view>
                                <view class="stat-divider"></view>
                                <view class="stat-group">
                                    <text class="stat-item">{{ item.category2Name || '未分类' }}</text>
                                </view>
                                <view class="stat-divider"></view>
                                <view class="stat-group">
                                    <text class="stat-item">{{ item.category3Name || '未分类' }}</text>
                                </view>
                            </view>
                        </view>
                        <view class="play-btn" @tap="goToGame" :data-data="item">
                            秒玩
                        </view>
                    </view>
                    <view class="divider"></view>
                </view>
            </view>

            <!-- 加载更多/无更多数据提示 -->
            <view class="load-more" v-if="myGame.length > 0">
                <text v-if="hasMore">加载更多...</text>
                <text v-else>没有更多了</text>
            </view>

            <!-- 空状态显示 -->
            <view v-if="myGame.length === 0" class="empty-state">
                暂无游戏记录
            </view>
        </scroll-view>

        <!-- 添加自定义登录提示框 -->
		<CustomConfirm
			:visible.sync="showLoginConfirm"
			title="温馨提示"
			content="亲，您还没登录，请先登录~"
			@confirm="handleLoginConfirm"
			@cancel="handleLoginCancel"
		/>
    </view>
</template>

<script>
import loginStatusUtils from '../../utils/loginStatusUtils';
import { getMyGameDetail } from '../../api/userGameApi';
import navigationBar from '../../components/navigation-bar/navigation-bar.vue';
import CustomConfirm from '../../components/CustomConfirm/CustomConfirm.vue';
import { addMyGame } from '../../api/userGameApi';
import { addClick, addOpen } from '../../api/getApi';

export default {
    components: {
        navigationBar,
        CustomConfirm
    },
    data() {
        return {
            myGame: [],
            isRefreshing: false,
            hasMore: true,
            page: 1,
            limit: 10,
            showLoginConfirm: false,
        };
    },
    onLoad() {
        console.log('myGame页面加载');
        this.loadGameData();
    },
    methods: {
        // 加载游戏数据
        loadGameData() {
            console.log('开始加载游戏数据');
            uni.showLoading({
                title: '加载中...'
            });
            
            getMyGameDetail({
                page: this.page,
                limit: this.limit
            }).then(res => {
                console.log('获取到游戏数据:', res);
                if (res.code === 0 && res.data && res.data.list) {
                    // 直接设置数据，不需要处理image字段
                    this.myGame = res.data.list;
                    
                    // 判断是否还有更多数据
                    this.hasMore = res.data.list.length === this.limit;
                    console.log('设置数据成功，数据长度:', this.myGame.length);
                } else {
                    console.log('返回数据格式有误:', res);
                    this.myGame = [];
                    this.hasMore = false;
                }
            }).catch(err => {
                console.error('获取游戏数据失败', err);
                uni.showToast({
                    title: '加载失败，请重试',
                    icon: 'none'
                });
            }).finally(() => {
                this.isRefreshing = false;
                uni.hideLoading();
                uni.stopPullDownRefresh();
                console.log('加载完成，当前数据:', this.myGame);
            });
        },

        // 下拉刷新
        onRefresh() {
            console.log('触发下拉刷新');
            this.isRefreshing = true;
            this.page = 1;
            this.loadGameData();
        },

        // 加载更多
        loadMore() {
            console.log('触发加载更多');
            if (this.hasMore) {
                this.page++;
                this.loadGameData();
            }
        },

        // 跳转到游戏
        goToGame(e) {
            console.log('点击游戏');
			// 检查登录状态
			if (!loginStatusUtils.checkLoginAndShowConfirm(this)) {
				return;
			}
			let itemdata = e.currentTarget.dataset.data;
			let loginType = 'app';
		
			//加入我的游戏
			addMyGame({
				kyyGameId: itemdata.kyyGameId || itemdata.id,
				kyyGameAppname: itemdata.kyyGameAppname || itemdata.appname,
				kyyGameLogo: itemdata.kyyGameLogo || itemdata.logoSquare || itemdata.logo,
				kyyGameUrl: itemdata.kyyGameUrl || itemdata.gameUrl
			}).then(res => {
				console.log('成功加入我的游戏',res);
			});

			//处于微信端时
			if (itemdata.appid && loginType === 'weixin') {
				uni.navigateToMiniProgram({
					appId: itemdata.appid,
					path: '?wxgamepro=CpsCBgAAoXkpQY9UXS9__OwV',
					envVersion: 'release',
					success: (res) => {
						let myGame = uni.getStorageSync('myGame');
						if (!myGame) {
							myGame = [];
						} else {
							myGame = JSON.parse(myGame).slice(0, 300);
						}
						if (!myGame.find((v) => v.id === itemdata.id)) {
							myGame = [itemdata, ...myGame];
						}
						uni.setStorageSync('myGame', JSON.stringify(myGame));
						this.setData({
							myGame: myGame
						});
						addOpen({
							id: itemdata.id
						});
					}
				});
				addClick({
					id: itemdata.id
				});
			}
			//处于APP端时
			else if ((itemdata.kyyGameUrl || itemdata.gameUrl) && loginType === 'app') {
				console.log('打开游戏',itemdata);
				uni.showToast({
					title: `正在为您打开游戏，请稍等~`,
					icon: 'none',
				});

				//对URL进行编码
				let encodedUrl = encodeURIComponent(itemdata.kyyGameUrl || itemdata.gameUrl);
				console.log('编码后URL:', encodedUrl);
                
				addClick({
					id: itemdata.kyyGameId || itemdata.id
				});
                
				uni.navigateTo({
					url: `/pages/webview/webview?src=${encodedUrl}&title=${itemdata.kyyGameAppname || itemdata.appname}`,
				}).then(res => {
					console.log('跳转成功', res);
					addOpen({
						id: itemdata.kyyGameId || itemdata.id
					});
                    // 跳转成功后，更新游戏数据
                    this.loadGameData();
				}).catch(err => {
					console.error('跳转失败', err);
				});
			}
			else {
				uni.showToast({
					title: `此游戏暂时无法打开，请稍后再试`,
					icon: 'none'
				});
			}
		},

        //登录提示框确认事件
		handleLoginConfirm() {
			uni.navigateTo({
				// 跳进登录页面
				url: '/pages/login/login'
			});
		},
		//登录提示框取消事件
		handleLoginCancel() {
			this.showLoginConfirm = false;
		}
    }
};
</script>

<style>
.page-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background-color: #f5f5f5;
}

.scroll-view {
    flex: 1;
    height: 0; /* 关键样式，确保scroll-view可以正确滚动 */
}

.game-list {
    padding: 16rpx 24rpx;
}

.game-item {
    margin-bottom: 24rpx;
}

.game-content {
    display: flex;
    align-items: center;
    padding: 20rpx;
    background-color: #ffffff;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.04);
    margin: 12rpx 0;
}

.game-logo {
    margin-right: 24rpx;
}

.logo-image {
    width: 120rpx;
    height: 120rpx;
    border-radius: 24rpx;
    box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
}

.game-info {
    flex: 1;
    margin-right: 12rpx;
}

.game-name {
    font-size: 36rpx;
    font-weight: 700;
    color: #222;
    margin-bottom: 16rpx;
    line-height: 1.5;
}

.game-desc {
    font-size: 28rpx;
    color: #444;
    margin-bottom: 16rpx;
    line-height: 1.5;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
    color: #555;
}

.game-stats {
    display: flex;
    /* align-items: center; */
    padding: 6rpx 0;
    font-size: 24rpx;
}

.stat-group {
    display: flex;
    align-items: center;
    color: #666;
    padding: 2rpx 0;
    flex: 1;
}

.stat-icon {
    width: 24rpx;
    height: 24rpx;
    margin-right: 3rpx;
}

.stat-item {
    font-size: 24rpx;
    color: #666;
    opacity: 0.9;
    white-space: normal;
    overflow: visible;
    line-height: 1.5;
}

.stat-divider {
    width: 1px;
    height: 20rpx;
    background-color: #e0e0e0;
    margin: 0 20rpx;
    flex-shrink: 0;
}

.play-btn {
    padding: 10rpx 30rpx;
    background-color: rgba(var(--Gred), var(--Ggreen), var(--Gblue), 0.15);
    color: var(--Color);
    border-radius: 100rpx;
    font-size: 26rpx;
    font-weight: bold;
    flex-shrink: 0;
    height: 50rpx;
    line-height: 50rpx;
    text-align: center;
}

.play-btn:active {
    transform: scale(0.95);
    opacity: 0.9;
}

.divider {
    height: 1rpx;
    background-color: #f0f0f0;
    margin: 0;
    opacity: 0.6;
}

.load-more {
    text-align: center;
    padding: 40rpx 0;
    color: #999;
    font-size: 26rpx;
    background: linear-gradient(to bottom, transparent, #f5f5f5);
}

.empty-state {
    text-align: center;
    padding: 120rpx 0;
    color: #999;
    font-size: 28rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
}
</style>
